using System;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
using Object = UnityEngine.Object;

namespace AutoInjector
{
    public static class Finder
    {
        public static T SearchInScene<T>(string filter = "") where T : Object
        {
            return SearchInScene(typeof(T), filter) as T;
        }
        
        public static Object SearchInScene(Type type, string filter = "")
        {
            Object[] objs = GameObject.FindObjectsOfType(type);
            if (objs == null || objs.Length == 0)
            {
                return null;
            }

            return string.IsNullOrEmpty(filter)
                ? objs.FirstOrDefault()
                : objs.FirstOrDefault(x => Regex.IsMatch(x.name, filter));
        }

        public static T Search<T>(this GameObject gameObject, string filter = "") where T : Object
        {
            return gameObject.Search(typeof(T), filter) as T;
        }

        public static Object Search(this GameObject gameObject, Type type, string filter = "")
        {
            var components = gameObject.GetComponentsInChildren(type);
            return string.IsNullOrEmpty(filter)
                ? components.FirstOrDefault()
                : components.FirstOrDefault(x => Regex.IsMatch(x.name, filter));
        }
    }
}